package cn.jkgly.jsapi.controller;
import cn.jkgly.jsapi.entity.Constants;
import cn.jkgly.jsapi.entity.WXTokenModel;
import cn.jkgly.jsapi.service.HttpClientUtil;
import cn.jkgly.jsapi.service.JsApiService;
import cn.jkgly.jsapi.service.RedisOperator;
import cn.jkgly.utils.JsonUtils;
import cn.jkgly.wxUser.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/jsapi")
public class jsApiController {
    @Autowired
    private RedisOperator redis;

    @Autowired
    @Qualifier("wxJsService")
    private JsApiService jsApiService;


    /**
     * 生成JSP页面的签名信息，第二步
     * @param tokenUrl
     * @param request
     * @return
     */
    @GetMapping(value = "/getSign")
    @ResponseBody
    public Map<String, String> scanJsApi(@Param("tokenUrl") String tokenUrl, HttpServletRequest request) {
        Map<String, String> res = jsApiService.sign(tokenUrl);
        return res;
    }

    /**
     * 获取公众号的access_token,写入Redis，是接口调用的第一步
     * @return
     */
    @GetMapping("/getAccessToken")
    public Result getAccessToken() {

        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> param = new HashMap<>(16);
        param.put("grant_type", "client_credential");
        param.put("appid", Constants.GZH_APPID);
        param.put("secret", Constants.GZH_SECURET);
        String wxResult = HttpClientUtil.doGet(url, param);
        System.out.println(wxResult);

        WXTokenModel model = JsonUtils.jsonToPoJo(wxResult, WXTokenModel.class);

        redis.set(Constants.GZH_TOKEN, model.getAccess_token(), Long.parseLong(model.getExpires_in()));

        return Result.ok(model);
    }

}
